package com.qianbao.qianbaobusiness.ui.cashier;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidbase.utils.RxUtils;
import com.baseandroid.config.Global;
import com.baseandroid.event.MerchantActivityEvent;
import com.baseandroid.event.MsgReadEvent;
import com.baseandroid.event.PaysuccessEvent;
import com.baseandroid.event.SwitchShopEvent;
import com.baseandroid.event.UnReadMsgEvent;
import com.baseandroid.gaode.GaoDeMap;
import com.baseandroid.mvp.BaseMvpFragment;
import com.baseandroid.retrofit.RxObserver;
import com.baseandroid.utils.MoneyUtil;
import com.qianbao.qianbaobusiness.BuildConfig;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.help.PermissionDialogHelper;
import com.qianbao.qianbaobusiness.json.CashierBean;
import com.qianbao.qianbaobusiness.json.MerchantAdvertsBean;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.ShopListInfo;
import com.qianbao.qianbaobusiness.json.UnReadMsgBean;
import com.qianbao.qianbaobusiness.json.UserPermession;
import com.qianbao.qianbaobusiness.ui.cashier.switchshop.SwitchShopActivity;
import com.qianbao.qianbaobusiness.ui.push.MessageListActivity;
import com.qianbao.qianbaobusiness.ui.webview.LoanWebviewActivity;
import com.qianbao.qianbaobusiness.ui.webview.SimpleWebViewActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.stat.StatService;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: Routee
 * @date 2018/6/11
 * @mail wangc4@qianbaocard.com
 * ------------1.本类由Routee开发,阅读、修改时请勿随意修改代码排版格式后提交到git。
 * ------------2.阅读本类时，发现不合理请及时指正.
 * ------------3.如需在本类内部进行修改,请先联系Routee,若未经同意修改此类后造成损失本人概不负责。
 */
public class CashierFragment extends BaseMvpFragment<CashierView, CashierPresenter> implements CashierView, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.tv_store_name)
    TextView           mTvStoreName;
    @BindView(R.id.tv_msg_count)
    TextView           mTvMsgCount;
    @BindView(R.id.srl)
    SwipeRefreshLayout mSrl;
    @BindView(R.id.tv_cash)
    TextView           mTvCash;
    @BindView(R.id.tv_counts)
    TextView           mTvCounts;
    @BindView(R.id.vp)
    Banner             mVp;
    @BindView(R.id.tv_zcd_desc)
    TextView           mTvZcdDesc;
    @BindView(R.id.tv_zcd_money)
    TextView           mTvZcdMoney;
    @BindView(R.id.rv)
    RecyclerView       mRv;
    @BindView(R.id.ll_zcd)
    LinearLayout       mLlZcd;
    private CashierAdapter mAdapter;
    private List<MerchantAdvertsBean.AdvertsBean> mList = new ArrayList<>();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SwitchShopEvent event) {
        initStoreName();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_cashier;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void setupView(View rootView) {
        mSrl.setColorSchemeColors(ContextCompat.getColor(getContext(), R.color.text_red));
        mSrl.setOnRefreshListener(this);
        initRecyclerView();
        initZcd();
        initStores();
        initStoreName();
        initData();
    }

    private void initRecyclerView() {
        LinearLayoutManager layout = new LinearLayoutManager(getContext());
        layout.setSmoothScrollbarEnabled(true);
        layout.setAutoMeasureEnabled(true);
        mRv.setLayoutManager(layout);
        mRv.setHasFixedSize(true);
        mRv.setNestedScrollingEnabled(false);
        mAdapter = new CashierAdapter(getContext());
        mRv.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.cashier_empty_view);
    }

    private void initZcd() {
        if (Global.getShopListInfo().loanInfo != null && Global.getShopListInfo().loanInfo
                                                                 .isEnable() && Global.getShopListInfo().getLoanMerchantInfo() != null) {
            for (UserPermession userPermession : Global.getShopListInfo()
                                                         .getLoanMerchantInfo().menuList) {
                if (TextUtils.equals("M100801", userPermession.menuCode)) {
                    mLlZcd.setVisibility(View.VISIBLE);
                    mTvZcdDesc.setText(Global.getShopListInfo().loanInfo.getDesc());
                    String amount = Global.getShopListInfo().loanInfo.getAmount();
                    amount = getString(R.string.rmb) + MoneyUtil.parseMoneyWithComma(amount);
                    mTvZcdMoney.setText(amount);
                    break;
                }
            }
        }
    }

    private void initData() {
        getPresenter().getMsgUnread(Global.getUserInfoBean()
                                            .getUser()
                                            .getUserNo(), "21", "ALL");
        getPresenter().getTotalStatics();
        getPresenter().getMerchantsAdverts();
        getPresenter().getMerchantActivity();
        getPresenter().getDistrict();
    }

    private void initStoreName() {
        StringBuilder sb = new StringBuilder();
        ShopListInfo selectedShopListInfo = Global.getSelectedShopListInfo();
        if (selectedShopListInfo.merchantList.size() <= 1) {
            mTvStoreName.setClickable(false);
            mTvStoreName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            if (selectedShopListInfo.merchantList.size() == 1) {
                mTvStoreName.setText(selectedShopListInfo.merchantList.get(0).merchantName);
            }
            return;
        }
        int count = 0;
        for (MerchantInfo merchantInfo : selectedShopListInfo.merchantList) {
            if (merchantInfo.isSelected) {
                sb.append(merchantInfo.merchantName).append(",");
                count++;
            }
        }
        String name = sb.substring(0, sb.lastIndexOf(","));
        if (count <= 1) {
            mTvStoreName.setText(name);
        } else if (count < selectedShopListInfo.merchantList.size()) {
            mTvStoreName.setText(name + "共" + count + "家店");
        } else {
            mTvStoreName.setText("已选全部门店");
        }
        mTvStoreName.requestLayout();
    }

    private void initStores() {
        ShopListInfo shopListInfo = Global.getShopListInfo();
        ShopListInfo selectedShopListInfo = Global.getSelectedShopListInfo();
        if (shopListInfo.merchantList.size() <= 1) {
            mTvStoreName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            if (shopListInfo.merchantList.size() == 0) {
                Global.setSelectedShopListInfo(new ShopListInfo());
                return;
            }
            shopListInfo.merchantList.get(0).isSelected = true;
        }
        if (selectedShopListInfo.merchantList == null || selectedShopListInfo.merchantList.size() == 0) {
            Global.setSelectedShopListInfo(shopListInfo);
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
    }

    @OnClick({R.id.tv_store_name, R.id.iv_msg, R.id.tv_cash_detail, R.id.tv_count_detail, R.id.rl_zcd_cashier})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_store_name:
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_home_select_store");
                }
                Intent i = new Intent(getActivity(), SwitchShopActivity.class);
                getActivity().startActivity(i);
                break;
            case R.id.iv_msg:
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_home_msg");
                }
                startActivity(new Intent(getActivity(), MessageListActivity.class));
                break;
            case R.id.tv_cash_detail:
                startActivity(new Intent(getActivity(), CashierListActivity.class));
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_home_cash_detail");
                }
                break;
            case R.id.tv_count_detail:
                startActivity(new Intent(getActivity(), SettlementActivity.class));
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_home_cash_settlement");
                }
                break;
            case R.id.rl_zcd_cashier:
                if (Global.mbLocSuccess) {
                    LoanWebviewActivity.gotoLoanWebView(getActivity(), Global.getUserInfoBean()
                                                                               .getLoanAccessToken(), "loan_apply", "商户贷", "cashier");
                    if (!BuildConfig.DEBUG) {
                        StatService.trackCustomEvent(Global.getContext(), "3_0_home_zcd");
                    }
                } else {
                    new RxPermissions(getActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                            .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                            .subscribe(new RxObserver<Boolean>() {
                                @Override
                                public void onNext(Boolean granted) {
                                    if (granted) {
                                        GaoDeMap.getInstance().startMap();
                                    } else {
                                        new PermissionDialogHelper(getActivity()).setMsg("没有定位权限，请去设置页添加相应权限").show();
                                    }
                                }
                            });
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void getMsgUnReadSuccess(UnReadMsgBean result) {
        if (mSrl.isRefreshing()) {
            mSrl.setRefreshing(false);
        }
        String count = result.getResult();
        if (TextUtils.isEmpty(count) || TextUtils.equals("0", count)) {
            mTvMsgCount.setVisibility(View.GONE);
            EventBus.getDefault().post(new UnReadMsgEvent(false));
        } else {
            mTvMsgCount.setVisibility(View.VISIBLE);
            mTvMsgCount.setText(count);
            EventBus.getDefault().post(new UnReadMsgEvent(true));
        }
    }

    @Override
    public void getTotalStaticsSuccess(CashierBean bean) {
        if (mSrl.isRefreshing()) {
            mSrl.setRefreshing(false);
        }
        mTvCash.setText(MoneyUtil.parseMoneyWithComma(bean.getTotalAmt()));
        mTvCounts.setText("共" + bean.getTotalNum() + "笔");
        mAdapter.resetData(bean.getDataList());
    }

    @Override
    public void onNetError() {
        if (mSrl.isRefreshing()) {
            mSrl.setRefreshing(false);
        }
    }

    @Override
    public void getMerchantActivitySuccess() {
        EventBus.getDefault().post(new MerchantActivityEvent());
    }

    @Override
    public void getMerchantAdvertsSuccess(MerchantAdvertsBean result) {
        List<MerchantAdvertsBean.AdvertsBean> list = result.getAdverts();
        if (list.size() == 0) {
            mVp.setVisibility(View.GONE);
            return;
        }
        boolean showActivity = Global.getMerchantActivityBean().getIsShow().equals("02");
        filtAdvertsList(showActivity, list);
        if (mList.size() < 1) {
            mVp.setVisibility(View.GONE);
            return;
        }
        mVp.setVisibility(View.VISIBLE);
        mVp.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mVp.setImageLoader(new GlideImageLoader());
        List<String> images = new ArrayList<>();
        for (MerchantAdvertsBean.AdvertsBean advertsBean : mList) {
            images.add(advertsBean.getImageUrl());
        }
        //设置图片集合
        mVp.setImages(images);
        //设置banner动画效果
        //        mVp.setBannerAnimation(Transformer.CubeOut);
        mVp.setBannerAnimation(Transformer.Default);
        //设置轮播时间
        mVp.setDelayTime(3500);
        //设置指示器位置（当banner模式中有指示器时）
        mVp.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        mVp.start();
        mVp.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putString(SimpleWebViewActivity.WEBVIEW_TITLE, mList.get(position).getContentName());
                bundle.putString(SimpleWebViewActivity.WEBVIEW_URL, mList.get(position).getContent());
                Intent intent = new Intent(getActivity(), SimpleWebViewActivity.class);
                intent.putExtras(bundle);
                getActivity().startActivity(intent);
                if (BuildConfig.DEBUG) {
                    return;
                }
                switch (position) {
                    case 0:
                        StatService.trackCustomEvent(Global.getContext(), "3_0_home_banner_1");
                        break;
                    case 1:
                        StatService.trackCustomEvent(Global.getContext(), "3_0_home_banner_2");
                        break;
                    case 2:
                        StatService.trackCustomEvent(Global.getContext(), "3_0_home_banner_3");
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void filtAdvertsList(boolean b, List<MerchantAdvertsBean.AdvertsBean> list) {
        mList.clear();
        for (MerchantAdvertsBean.AdvertsBean bean : list) {
            if (bean.getContentName().equals("零费率活动") && !b) {
                continue;
            }
            mList.add(bean);
        }
    }

    @Override
    public void onRefresh() {
        getPresenter().getTotalStatics();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PaysuccessEvent paysuccess) {
        // 收到推送成功进行刷新
        getPresenter().getTotalStatics();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgReadEvent event) {
        getPresenter().getMsgUnread(Global.getUserInfoBean().getUser().getUserNo(), "21", "ALL");
    }
}
